<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios 拦截器</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
</head>

<body>
  <h2>axios 拦截器</h2>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      // 创建 axios 实例
      const instance = axios.create({
        baseURL: '/',
        timeout: 10000,
      })

      // 设置请求拦截器(第二参数一般不会调用，除非，配置了第三个参数或者多个同类型拦截器，第二个出现错误，会触发第一个拦截器的第二个参数)
      instance.interceptors.request.use(config => {
        NProgress.start()
        // 添加 token 请求头
        const token = localStorage.getItem('token')
        if (!token) {
          return Promise.reject({
            code: 006,
            msg: '您未登录，请先登录！'
          })
        }
        config.headers.Authorization = token
        return config;
      }, error => {
        return Promise.reject(error) // 相当于从 .then 中返回一个失败的 Promise 用于处理失败的结果
      })

      // 设置响应拦截器
      instance.interceptors.response.use(res => {
        NProgress.done()
        const {
          data
        } = res
        // 判读响应成功返回的结果
        if (data.code !== 100) { // 结果不是预期
          return Promise.reject(data)
        }
        return res.data
      }, error => {
        return Promise.reject(error)
      })

      InitializationPage()
      async function InitializationPage() {
        try {
          const result = await instance.get('/validation/initialData')
          console.log(result)
        } catch (error) {
          switch (error.code) {
            case 006:
            case 405:
            case 406:
              signInStatus(error);
              break;
            default:
              console.log(error)
          }
        }
      }

      function signInStatus({
        msg
      }) {
        alert(msg)
        NProgress.done()
        location.href = '/signIn'
      }
    })
  </script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</body>

</html>